/**
	Pulsar engine. Core.
	File find interface - windows extension

	Copyright (C) 2013-2014 Dmitry Dolgov

	This program is free software; you can redistribute it and/or modify it under the terms of the
	GNU General Public License as published by the Free Software Foundation; either version 2 of
	the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
	without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
	See the GNU General Public License for more details.
*/

#include <pulsar/pulsar.h>
#include <pulsar/src/pulsar_intr.h>

pl::FindFileWin::FindFileWin(const pl::Filepath& mask) :
_bFileFound(false),
_bFirstCall(true)
{
	WIN32_FIND_DATA findData;

	_hFind = FindFirstFile(mask.get(), &findData);

	if (_hFind != INVALID_HANDLE_VALUE)
	{
		_bFileFound = true;

		_fileName.set(findData.cFileName);
		_size = findData.nFileSizeHigh;
		_size = (_size << 32) | findData.nFileSizeLow;

		convertWin2Fs(findData.ftCreationTime, _dateCreate);
		convertWin2Fs(findData.ftLastWriteTime, _dateModify);
		convertWin2Fs(findData.ftLastAccessTime, _dateAccess);
		FileManagerImplWin::convertWin2Fs(findData.dwFileAttributes, _attrib);
	}
	return;
}

pl::FindFileWin::~FindFileWin()
{
	if (_hFind != INVALID_HANDLE_VALUE)
	{
		FindClose(_hFind);
	}
	return;
}

bool pl::FindFileWin::isFinished()
{
	WIN32_FIND_DATA findData;

	if (!_bFileFound || _hFind == INVALID_HANDLE_VALUE)
	{
		return true;
	}

	if (_bFirstCall)
	{
		_bFirstCall = false;
		return false;
	}

	if (!FindNextFile(_hFind, &findData))
	{
		_bFileFound = false;
		return true;
	}
	_fileName.set(findData.cFileName);
	_size = findData.nFileSizeHigh;
	_size = (_size << 32) | findData.nFileSizeLow;

	convertWin2Fs(findData.ftCreationTime, _dateCreate);
	convertWin2Fs(findData.ftLastWriteTime, _dateModify);
	convertWin2Fs(findData.ftLastAccessTime, _dateAccess);
	FileManagerImplWin::convertWin2Fs(findData.dwFileAttributes, _attrib);
	return false;
}

const pl::DateTime& pl::FindFileWin::getFileDate(FileDateType type) const
{
	PL_ASSERTW(isFound(), PL_T("No more files found"));
	switch (type)
	{
		case FILE_DATE_CREATE:
			return _dateCreate;
		case FILE_DATE_MODIFY:
			return _dateModify;
		case FILE_DATE_ACCESS:
			return _dateAccess;
	}
	PL_ASSERTW(false, PL_T("Wrong date type"));
	return _dateCreate;
}

//
// End of file 'pulsar_file_find_win.cpp'
//
